package com.cross.test.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.jaxb.JAXBReader;

public class ConfigXml {

	public static void main(String[] args) throws DocumentException, FileNotFoundException {
		read("e:/test/config.xml");
	}

	public static List<BaseConnBean> read() throws DocumentException, FileNotFoundException {
		return read("e:/test/config.xml");
	}

	public static List<BaseConnBean> read(String path) throws DocumentException, FileNotFoundException {
//		String rpath = ConfigXml.class.getResource("./").getPath().substring(1)
//				+ path;
		String rpath = path;
		FileInputStream fi = null;
		List<BaseConnBean> pools = new ArrayList<BaseConnBean>();
		File file = new File(rpath);
		fi = new FileInputStream(file);
		JAXBReader jaxbReader = new JAXBReader(path);
		Document doc = jaxbReader.read(fi);
		Element root = doc.getRootElement();
		List list = root.elements();
		Element pool = null;
		Iterator allPool = list.iterator();
		while (allPool.hasNext()) {
			pool = (Element) allPool.next();
			BaseConnBean bcBean = new BaseConnBean();
			bcBean.setName(pool.elementTextTrim("name"));

			bcBean.setUsername(pool.elementTextTrim("username"));
			bcBean.setPassword(pool.elementTextTrim("password"));
			bcBean.setJdbcurl(pool.elementTextTrim("jdbcurl"));
			try {
				bcBean.setMax(Integer.parseInt(pool.elementTextTrim("max")));
			} catch (NumberFormatException e) {
				bcBean.setMax(0);
			}
			try {
				bcBean.setWait(Long.parseLong(pool.elementTextTrim("wait")));
			} catch (NumberFormatException e) {
				bcBean.setWait(-1L);
			}
			bcBean.setDriver(pool.elementTextTrim("driver"));
			pools.add(bcBean);
		}
		return pools;
	}
}
